package com.lxw.test1.mutiDownload;

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.*;


// 注释部分代码为：使用executors创建线程池

public class TestPool {
    //核心线程数
    static int corePoolSize = 3;
    //最大线程数
    static int maximumPoolSize = 6;
    //超过 corePoolSize 线程数量的线程最大空闲时间
    static long keepAliveTime = 2;
    //以秒为时间单位
    static TimeUnit unit = TimeUnit.SECONDS;
    //对应创建工作队列，用于存放提交的等待执行任务，此处填写队列大小
    static int queueSize = 20000;
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        // 定义开始时间
        long start = System.currentTimeMillis();

        // 1、创建服务，创建线程池

//        int coreSize = 5;
//        ExecutorService service = Executors.newFixedThreadPool(coreSize);


        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                new ArrayBlockingQueue<>(queueSize),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // 读取txt文件
        String urlText = FileUtils.readFileToString(new File("D:/CodeReference/img/1234.txt"), "UTF-8");
        String[] urls = urlText.split("\n");

        // 开始执行
        for (int i = 0; i < urls.length-5; i = i + 1) {
            MyCallable t1 = new MyCallable(urls[i]);

            Future s1 = executor.submit(t1);
//            Future s1 = service.submit(t1);

            Object ss1 = s1.get();

            System.out.println("executor"+ss1);
        }


//         2、关闭连接
        executor.shutdown();
//        service.shutdown();
        long end = System.currentTimeMillis();
        System.out.println("线程下载数据用时:" + (end - start) + "ms");
    }
}
